<template>
  <!--列表-->
  <router-exact-view name="send">
    <div style="width: 100%" class="template-list-page-container">
      <div class="search-area">
        <search-form-container>
          <el-form :inline="true" :model="searchForm">
            <el-form-item label="教师姓名">
              <el-input
                v-model="searchForm.teacherName"
                placeholder="请输入教师姓名"
              />
            </el-form-item>
            <el-form-item label="学生姓名">
              <el-input
                v-model="searchForm.studentName"
                placeholder="请输入学生姓名"
              />
            </el-form-item>
            <el-form-item label="所属学期">
              <el-select v-model="searchForm.schoolTermId" placeholder="请选择学期">
                <el-option label="全部" :value="0" />
                <el-option v-for="item in termOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="searchForm.status" placeholder="请选择送教状态">
                <el-option label="全部" :value="-1" />
                <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="handlePageChange(1)"
              >查 询</el-button>
              <el-button @click="resetSearchForm">重 置</el-button>
            </el-form-item>
          </el-form>
        </search-form-container>
      </div>
      <my-table
        v-loading="loading"
        :columns="columns"
        :data-source="data"
        :pagination="pagination"
        :btn-options="btnOptions"
        title="送教任务列表"
        @page-change="handlePageChange"
      >
        <div slot="table-btn">
          <el-button v-permission="[settings.managePerm]" type="primary" @click="addSend">新建送教任务</el-button>
        </div>
      </my-table>
    </div>
    <el-dialog title="送教评价" :visible.sync="rankVisible">
      <el-form :model="form">
        <el-form-item label="评分" :label-width="formLabelWidth">
          <el-rate
            v-model="form.score"
            style="margin-top: 7px;"
            show-text
            text-color="#ff9900"
            :texts="text"
            :max="3"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rankVisible = false">取 消</el-button>
        <el-button type="primary" @click="doRank">确 定</el-button>
      </div>
    </el-dialog>
  </router-exact-view>
</template>

<script>
import MyTable from '@/components/my-table/index'
import SearchFormContainer from '@/components/search-form-container/index'
import RouterExactView from '@/components/routerExactView'
import { getTaskList, setArticleStatus, delTask, rankTask, getTaskDetail } from '@/api/task'
import { getAllTerm } from '@/api/basic'
import settings from '@/settings'
import { sendColumns } from '../columns'
import { statusOptions } from '../attr'

export default {
  components: { RouterExactView, MyTable, SearchFormContainer },
  data() {
    const that = this
    return {
      settings,
      statusOptions,
      activeName: '1',
      // 评分弹窗相关
      rankVisible: false,
      form: {},
      formLabelWidth: '120px',
      text: [],
      /* 列表相关 */
      termOptions: [],
      columns: sendColumns,
      data: [],
      searchForm: {},
      loading: false,
      pagination: {
        current: 1,
        pageSize: 10,
        total: 0
      },
      btnOptions: [
        {
          name: '查看详情',
          handler: function(row) {
            that.$router.push({
              path: `/task/send/detail/${row.id}`
            })
          }
        },
        {
          name: '删除',
          v_if: row => row.status === 0,
          permission: [settings.managePerm],
          handler: function(row) {
            that.deleteTask(row)
          }
        },
        {
          name: '期末评价',
          v_if: row => row.status === 2,
          permission: [settings.managePerm],
          handler: function(row) {
            that.openRankDialog(row)
          }
        }
      ]
    }
  },
  mounted() {
    if (this.$route.name === 'send') {
      this.handlePageChange()
      this.getTermList()
    }
  },
  methods: {
    handleClick() {},
    updateArticleStatus(articleId, type) {
      const that = this
      this.$confirm(`确认${type === 1 ? '启用' : '禁用'}当前文章?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          const res = await setArticleStatus({
            articleId,
            articleStatus: type
          })
          if (res && typeof res === 'boolean') {
            that.$alert(`${type === 1 ? '启用' : '禁用'}文章成功！`, {
              confirmButtonText: '确定',
              callback: (action) => {
                that.handlePageChange()
              }
            })
          }
        })
        .catch(() => {
          console.log('已取消启用禁用操作')
        })
    },
    addSend() {
      this.$router.push({ path: `/task/send/add` })
    },
    async handlePageChange(current, size) {
      if (current) {
        this.pagination.current = current
      }
      if (size) {
        this.pagination.pageSize = size
      }
      this.loading = true
      try {
        const params = JSON.parse(JSON.stringify(this.searchForm || {}))
        if (!params.studentName) {
          delete params.studentName
        }
        if (!params.teacherName) {
          delete params.teacherName
        }
        if (params.status === -1) {
          delete params.status
        }
        if (!params.schoolTermId) {
          delete params.schoolTermId
        }
        const res = await getTaskList({
          ...params,
          pageNum: this.pagination.current,
          pageSize: this.pagination.pageSize
        })
        if (res && res.list) {
          this.data = res.list
          this.pagination = {
            current: res.pageNum,
            pageSize: res.pageSize,
            total: res.totalElements
          }
        }
        this.loading = false
      } catch (err) {
        this.loading = false
      }
    },
    resetSearchForm() {
      this.searchForm = {}
      this.handlePageChange(1)
    },
    async getTermList() {
      try {
        const res = await getAllTerm({
          pageNum: 1,
          pageSize: 1000
        })
        if (res && res.length) {
          this.termOptions = res.map(v => ({
            label: v.name,
            value: v.id
          }))
        }
      } catch (err) {
        console.log(err)
      }
    },
    async deleteTask(row) {
      const that = this
      this.$confirm('确定要删除该送教任务？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async() => {
        try {
          const res = await delTask({
            id: row.id
          })
          if (res) {
            that.$message({
              message: `删除送教任务成功！`,
              type: 'success'
            })
            that.handlePageChange(that.pagination.current)
          }
        } catch (err) {
          console.log(err)
        }
      })
    },
    openRankDialog(row) {
      const that = this
      this.getDetail(row.id, data => {
        that.rankVisible = true
        that.form = {
          outworkId: row.id,
          score: data.adminScore || 0
        }
      })
    },
    async getDetail(id, cb) {
      try {
        const res = await getTaskDetail({ id })
        if (res && cb) {
          cb(res)
        }
      } catch (err) {
        console.log('接口出错')
      }
    },
    async doRank() {
      if (this.form.score) {
        try {
          const res = await rankTask(this.form)
          if (res) {
            this.$message({
              message: `管理员评价成功！`,
              type: 'success'
            })
            this.rankVisible = false
            this.handlePageChange(this.pagination.current)
          }
        } catch (err) {
          console.log(err)
        }
      } else {
        this.$message.error('请先评分')
      }
    }
  }
}
</script>
<style scoped lang="less">
@import "../../common.css";
/* 查询条件容器的样式 */
.search-area {
  padding: 16px 16px 0;
  margin-bottom: 8px;
  background: #fff;
}
.tab-list {
  background: #fff;
  padding: 15px 15px 0;
  overflow: hidden;
  .tab-list-title {
    float: left;
    color: #303133;
    font-size: 16px;
    font-weight: bold;
    line-height: 32px;
  }
  .tab-list-btn {
    float: right;
  }
}
.el-tabs-list {
  background: #fff;
  padding: 0 15px;
  .child-my-table {
    ::v-deep .my-table-area {
      padding: 0;
    }
  }
}
</style>
